import React, { useCallback, useEffect, useState } from 'react'
import CollaborationHistory from '@tiptap-pro/extension-collaboration-history'
import { Button } from "@/components/Tiptap/tiptap-ui-primitive/button"
import { VersioningModal } from './VersioningModal'
import { renderDate } from './utils'
import './style.less'

// 创建历史版本控制扩展的配置函数
export const createHistoryExtension = (provider, onUpdate) => {
  return CollaborationHistory.configure({
    provider,
    onUpdate: (data) => {
      if (onUpdate) {
        onUpdate({
          versions: data.versions,
          versioningEnabled: data.autoVersioning,
          latestVersion: data.version,
          currentVersion: data.currentVersion,
          synced: data.synced,
          status: data.status,
          lastSaved: data.lastSaved,
        })
      }
    },
  })
}

// 历史版本控制 Hook
export const useDocumentHistory = (editor, provider) => {
  const [latestVersion, setLatestVersion] = useState(null)
  const [currentVersion, setCurrentVersion] = useState(null)
  const [versions, setVersions] = useState([])
  const [isAutoVersioning, setIsAutoVersioning] = useState(false)
  const [hasChanges, setHasChanges] = useState(false)
  const [synced, setSynced] = useState(false)

  // 处理版本更新
  const handleVersionUpdate = useCallback((data) => {
    setVersions(data.versions || [])
    setIsAutoVersioning(data.versioningEnabled || false)
    setLatestVersion(data.latestVersion)
    setCurrentVersion(data.currentVersion)
    setSynced(data.synced || false)
  }, [])

  // 监听文档变化
  useEffect(() => {
    if (!provider || !provider.document) return

    const onUpdate = () => {
      setHasChanges(true)
    }

    const onSynced = () => {
      provider.document.on('update', onUpdate)
    }

    provider.on('synced', onSynced)

    return () => {
      provider.off('synced', onSynced)
      if (provider.document) {
        provider.document.off('update', onUpdate)
      }
    }
  }, [provider])

  // 创建新版本
  const saveVersion = useCallback((name) => {
    if (!editor || !name) return false
    
    try {
      editor.commands.saveVersion(name)
      setHasChanges(false)
      return true
    } catch (error) {
      console.error('Failed to save version:', error)
      return false
    }
  }, [editor])

  // 切换自动版本控制
  const toggleVersioning = useCallback(() => {
    if (!editor) return false
    
    try {
      editor.commands.toggleVersioning()
      return true
    } catch (error) {
      console.error('Failed to toggle versioning:', error)
      return false
    }
  }, [editor])

  // 恢复到指定版本
  const revertToVersion = useCallback((version, versionData) => {
    if (!editor || version === null) return false
    
    try {
      const versionTitle = versionData ? versionData.name || renderDate(versionData.date) : `Version ${version}`
      editor.commands.revertToVersion(
        version, 
        `Revert to ${versionTitle}`, 
        `Unsaved changes before revert to ${versionTitle}`
      )
      return true
    } catch (error) {
      console.error('Failed to revert to version:', error)
      return false
    }
  }, [editor])

  return {
    // 状态
    versions,
    latestVersion,
    currentVersion,
    isAutoVersioning,
    hasChanges,
    synced,
    
    // 方法
    saveVersion,
    toggleVersioning,
    revertToVersion,
    handleVersionUpdate,
  }
}

// 历史版本控制面板组件
export const HistoryPanel = ({ 
  editor, 
  provider,
  className = '',
  showAutoVersioning = true,
  showManualVersioning = true,
}) => {
  const {
    versions,
    latestVersion,
    currentVersion,
    isAutoVersioning,
    hasChanges,
    saveVersion,
    toggleVersioning,
    revertToVersion,
    handleVersionUpdate,
  } = useDocumentHistory(editor, provider)

  const [versioningModalOpen, setVersioningModalOpen] = useState(false)
  const [commitDescription, setCommitDescription] = useState('')

  // 处理新版本创建
  const handleNewVersion = useCallback((e) => {
    e.preventDefault()
    if (!commitDescription.trim()) return
    
    const success = saveVersion(commitDescription.trim())
    if (success) {
      setCommitDescription('')
    }
  }, [commitDescription, saveVersion])

  // 显示版本历史模态框
  const showVersioningModal = useCallback(() => {
    setVersioningModalOpen(true)
  }, [])

  // 关闭版本历史模态框
  const handleVersioningClose = useCallback(() => {
    setVersioningModalOpen(false)
  }, [])

  // 处理版本恢复
  const handleRevert = useCallback((version, versionData) => {
    const success = revertToVersion(version, versionData)
    if (success) {
      setVersioningModalOpen(false)
    }
  }, [revertToVersion])

  return (
    <>
      <VersioningModal
        versions={versions}
        isOpen={versioningModalOpen}
        onClose={handleVersioningClose}
        onRevert={handleRevert}
        currentVersion={currentVersion}
        latestVersion={latestVersion}
        provider={provider}
      />
      
      <div className={`history-panel ${className}`}>
        {showAutoVersioning && (
          <div className="option-group">
            <div className="label-large">自动版本控制</div>
            <div className="switch-group">
              <label>
                <input
                  type="radio"
                  name="auto-versioning"
                  onChange={() => !isAutoVersioning && toggleVersioning()}
                  checked={isAutoVersioning}
                />
                启用
              </label>
              <label>
                <input
                  type="radio"
                  name="auto-versioning"
                  onChange={() => isAutoVersioning && toggleVersioning()}
                  checked={!isAutoVersioning}
                />
                禁用
              </label>
            </div>
          </div>
        )}
        
        {showManualVersioning && (
          <div className="option-group">
            <div className="label-large">手动版本控制</div>
            <div className="label-small">对文档进行修改后，可以手动保存新版本。</div>
            <form className="commit-panel" onSubmit={handleNewVersion}>
              <input 
                disabled={!hasChanges} 
                type="text" 
                placeholder="版本名称" 
                value={commitDescription} 
                onChange={(e) => setCommitDescription(e.target.value)}
              />
              <Button 
                disabled={!hasChanges || commitDescription.trim().length === 0} 
                type="submit"
                data-style="default"
              >
                创建版本
              </Button>
            </form>
          </div>
        )}
        
        <div className="option-group">
          <Button 
            className="primary" 
            type="button" 
            onClick={showVersioningModal}
            data-style="default"
          >
            显示历史记录
          </Button>
        </div>
      </div>
    </>
  )
}

// 简化的历史按钮组件（用于工具栏）
export const HistoryButton = ({ 
  editor, 
  provider,
  onHistoryClick,
  children = "历史版本"
}) => {
  const {
    versions,
    latestVersion,
    currentVersion,
    revertToVersion,
  } = useDocumentHistory(editor, provider)

  const [versioningModalOpen, setVersioningModalOpen] = useState(false)

  const showVersioningModal = useCallback(() => {
    if (onHistoryClick) {
      onHistoryClick()
    } else {
      setVersioningModalOpen(true)
    }
  }, [onHistoryClick])

  const handleVersioningClose = useCallback(() => {
    setVersioningModalOpen(false)
  }, [])

  const handleRevert = useCallback((version, versionData) => {
    const success = revertToVersion(version, versionData)
    if (success) {
      setVersioningModalOpen(false)
    }
  }, [revertToVersion])

  return (
    <>
      <VersioningModal
        versions={versions}
        isOpen={versioningModalOpen}
        onClose={handleVersioningClose}
        onRevert={handleRevert}
        currentVersion={currentVersion}
        latestVersion={latestVersion}
        provider={provider}
      />
      
      <Button
        data-style="ghost"
        onClick={showVersioningModal}
        title="查看文档历史版本"
      >
        {children} 
      </Button>
    </>
  )
}

export default {
  createHistoryExtension,
  useDocumentHistory,
  HistoryPanel,
  HistoryButton,
}